package com.moyq5.permit.center.web.controller;

import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.servlet.AbstractShiroFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.moyq5.mvc.framework.general.Body;
import com.moyq5.mvc.framework.general.Sorting;
import com.moyq5.mvc.framework.jackson.result.ListResult;
import com.moyq5.mvc.framework.jackson.result.ObjectResult;
import com.moyq5.mvc.framework.jackson.result.StatusResult;
import com.moyq5.mvc.framework.jackson.result.StatusResult.Status;
import com.moyq5.mvc.framework.utils.StringUtils;
import com.moyq5.permit.center.bean.entity.SysPermit;
import com.moyq5.permit.center.bean.enums.SysPlatform;
import com.moyq5.permit.center.bean.search.SysPermit4Search;
import com.moyq5.permit.center.feign.client.SysPermitFeign;
import com.moyq5.permit.center.web.MyErrorCode;
import com.moyq5.permit.center.web.MyException;
import com.moyq5.permit.center.web.ShiroAppliedPathsResetProcessor;
import com.moyq5.permit.center.web.ShiroConfiguration;
import com.moyq5.permit.center.web.form.SysPermitForm4Update;
import com.moyq5.permit.center.web.jackson.filter.SysPermitFilter;

/**
 * 权限信息
 * @author Moyq5
 * @date 2019年7月10日
 */
@RestController
@RequestMapping("/permit")
public class SysPermitController extends BaseController {
	
	private static Logger log = LoggerFactory.getLogger(SysPermitController.class);
	
	@Autowired
	private SysPermitFeign permitFeign;
	@Autowired
	private ShiroFilterFactoryBean shiroFilterFactoryBean;
	
	/**
	 * @author Moyq5
	 * @date 2019年7月10日
	 * @param permit4s
	 * @param si
	 * @return
	 * @throws JsonProcessingException
	 */
	@GetMapping(value="/list/{plat}/!/**", produces={MediaType.APPLICATION_JSON_UTF8_VALUE})
	@ResponseBody
	public String list(SysPermit4Search permit4s, Sorting si, @PathVariable("plat") int platform) throws JsonProcessingException {
		log.debug("查询权限信息>>>list(SysPermit4Search, Sorting)");
		permit4s.setPlatform(SysPlatform.values()[platform]);
		return toJson(permitFeign.list(new Body<SysPermit4Search, Sorting>(permit4s, si)), SysPermitFilter.get());
	}
	
	/**
	 * @author Moyq5
	 * @date 2019年8月14日
	 * @param permit4s
	 * @param si
	 * @return
	 * @throws JsonProcessingException
	 */
	@GetMapping(value="/list/cross/{plat}/!/**", produces={MediaType.APPLICATION_JSON_UTF8_VALUE})
	@ResponseBody
	public String list4Grant(SysPermit4Search permit4s, Sorting si, @PathVariable("plat") int platform) throws JsonProcessingException {
		log.debug("查询权限信息>>>list(SysPermit4Search, Sorting)");
		permit4s.setPlatform(SysPlatform.AUTH);
		if (platform == SysPlatform.COMPANY.ordinal()) {// 运营平台可管理代理商、商户、门店等账号和权限
			permit4s.setTagGt("" + SysPlatform.AUTH.ordinal());
		} else {
			permit4s.setTag("" + platform);
		}
		
		return toJson(permitFeign.list(new Body<SysPermit4Search, Sorting>(permit4s, si)), SysPermitFilter.get());
	}
	
	/**
	 * @author Moyq5
	 * @date 2019年7月10日
	 * @param permit
	 * @return
	 */
	@PutMapping("/add/{plat}/!/**")
	@ResponseBody
	public ObjectResult<Long> add(@RequestBody SysPermit permit, @PathVariable("plat") int platform) {
		log.debug("添加权限信息>>>add(SysPermit)");
		permit.setPlatform(SysPlatform.values()[platform]);
		ObjectResult<Long> result = permitFeign.create(permit);
		if (result.getStatus() == Status.OK) {
			updatePathDefinition(platform);
		}
		return result;
	}
	
	/**
	 * 
	 * @author Moyq5
	 * @date 2019年7月10日
	 * @param permit
	 * @return
	 */
	@PatchMapping("/edit/{plat}/!/**")
	@ResponseBody
	public StatusResult edit(@RequestBody @Validated SysPermitForm4Update permit, @PathVariable("plat") int platform) {
		log.debug("更新权限信息>>>edit(SysPermit)");
		permit.setPlatform(SysPlatform.values()[platform]);
		StatusResult result = permitFeign.update(permit);
		if (result.getStatus() == Status.OK) {
			updatePathDefinition(platform);
		}
		return result;
	}
	
	/**
	 * @author Moyq5
	 * @date 2019年7月11日
	 * @param permitId
	 * @return
	 */
	@DeleteMapping("/del/{plat}/!/**")
	@ResponseBody
	public StatusResult del(@RequestBody Long permitId, @PathVariable("plat") int platform) {
		log.debug("删除权限信息>>>del(permitId)");
		ObjectResult<SysPermit> permitRst = permitFeign.one(permitId);
		if (permitRst.getStatus() != Status.OK) {
			return permitRst;
		}
		if (null == permitRst.getData() || permitRst.getData().getPlatform().ordinal() != platform) {
			throw new MyException(MyErrorCode.C9998);
		}
		StatusResult result = permitFeign.remove(permitId);
		if (result.getStatus() == Status.OK) {
			updatePathDefinition(platform);
		}
		return result;
	}
	
	/**
	 * 使权限配置实时生效
	 * @author Moyq5
	 * @date 2019年8月2日
	 * @param platform
	 * @see {@link ShiroConfiguration}
	 */
	private void updatePathDefinition(int platform) {
		if (platform != SysPlatform.AUTH.ordinal()) {
			return;
		}
		
		SysPermit4Search permit4s = new SysPermit4Search();
		permit4s.setPlatform(SysPlatform.AUTH);
		ListResult<SysPermit> listRst = permitFeign.list(new Body<SysPermit4Search, Sorting>(permit4s, new Sorting()));
		
		Map<String, String> map = new LinkedHashMap<String, String>();
		map.clear();
	    map.put("/login/**", "myAuthc");
	    map.put("/admin/auth", "anon");
	    map.put("/admin/login/**", "anon");
	    listRst.getData().forEach(permit -> {
	    	if (!StringUtils.isEmpty(permit.getPath()) && !StringUtils.isEmpty(permit.getAuth())) {
	    		map.put(permit.getPath(), permit.getAuth());
	    	}
	    });
	    map.put("/**", "myAuthc");
	    
	    shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
	    
	    
	    AbstractShiroFilter shiroFilter = null;  
        try {  
            shiroFilter = (AbstractShiroFilter) shiroFilterFactoryBean.getObject();  
        } catch (Exception e) { 
        	log.warn("", e);
        	return;
        }
  
        PathMatchingFilterChainResolver filterChainResolver = (PathMatchingFilterChainResolver) shiroFilter  
                .getFilterChainResolver();  
        DefaultFilterChainManager manager = (DefaultFilterChainManager) filterChainResolver  
                .getFilterChainManager();  
  
        manager.getFilterChains().clear();  
		manager.getFilters().forEach((key, filter) -> {
			if (filter instanceof ShiroAppliedPathsResetProcessor) {
				((ShiroAppliedPathsResetProcessor)filter).clearAppliedPaths();
			}
		});
	    for (Map.Entry<String, String> entry : map.entrySet()) {
            manager.createChain(entry.getKey(), entry.getValue());
        }
	    
	}
	
}
